import * as React from 'react';
import PropTypes from 'prop-types';

export default class LazyLoadModule extends React.Component {
  constructor() {
    super();
    this.state = {
      module: null,
    };
  }

  componentDidCatch(error) {
    this.setState({ hasError: error });
  }

  async componentDidMount() {
    try {
      const { resolve, name } = this.props;
      const reducers = await resolve();
      const { store } = this.context;
      if (name && store && reducers) store.registerDynamicModule({ name, reducers });
      this.setState({ module });
    } catch (error) {
      this.setState({ hasError: error });
    }
  }

  componentWillUnmount() {
    const { module } = this.state;
    const { store } = this.context;
    const { name } = module;
    if (store && name) store.unRegisterDynamicModule(name);
  }

  render() {
    const { module, hasError } = this.state;
    const { resolve, component, ...rest } = this.props;
    if (hasError) return <div>{hasError.message}</div>;
    if (!module) return <div>Loading module...</div>;

    if (this.props.children) return React.createElement(this.props.children, rest);

    return <div>Module loaded</div>;
  }
}

LazyLoadModule.contextTypes = {
  store: PropTypes.object,
};

LazyLoadModule.propTypes = {
  resolve: PropTypes.instanceOf(Promise).isRequired,
  name: PropTypes.string.isRequired,
};
